<template>
  <a-layout>
    <a-layout-header 
      style="background: #fff; padding: 0 50px;"
      key="layout-header"
    >
      <a-menu
        mode="horizontal"
        :selected-keys="[currentMenuKey]"
        :key="menuKey"
        theme="light"
        :style="{ lineHeight: '64px' }"
      >
        <a-menu-item key="/" @click="$router.push('/')">
          首页
        </a-menu-item>
        <a-menu-item key="/problems" @click="$router.push('/problems')">
          题库
        </a-menu-item>
        <a-menu-item key="/blog" @click="$router.push('/blog')">
          博客
        </a-menu-item>
        <a-menu-item key="/chat" @click="$router.push('/chat')">
          消息
        </a-menu-item>
        
        <!-- 全局搜索 -->
        <div class="search-container">
          <GlobalSearch />
        </div>
        
        <div class="user-actions">
          <template v-if="!isLoggedIn">
            <a-button type="primary" @click="login">
              登录
            </a-button>
            <a-button @click="register">
              注册
            </a-button>
          </template>
          <template v-else>
              <div class="user-info">
              <div class="native-dropdown">
                <div 
                  class="avatar"
                >
                  <span class="username">{{ userStats.name }}</span>
                  <a-avatar 
                    :size="40" 
                    :src="userStats.avatar"
                    style="margin-left: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.15)"
                  />
                </div>
                <div class="dropdown-content" >
                    <div class="dropdown-item" @click="handleProfileMenuClick({ key: 'profile' })">我的信息</div>
                    <div class="dropdown-item" @click="handleProfileMenuClick({ key: 'problems' })">题目记录</div>
                    <div class="dropdown-item" @click="handleProfileMenuClick({ key: 'blogs' })">我的博客</div>
                    <div class="dropdown-item" @click="handleProfileMenuClick({ key: 'friends' })">好友列表</div>
                    <div class="dropdown-item danger" @click="handleProfileMenuClick({ key: 'logout' })">退出登录</div>
                </div>
              </div>
            </div>
          </template>
        </div>
      </a-menu>
    </a-layout-header>

    <a-layout-content>
      <router-view />
    </a-layout-content>
  </a-layout>
</template>

<script>
import { 
  MessageOutlined,
  UserOutlined,
  BookOutlined, 
  FileTextOutlined,
  TeamOutlined,
  LogoutOutlined
} from '@ant-design/icons-vue'
import { useUserStore } from '@/stores/user'
import { useRoute, useRouter } from 'vue-router'
import { ref, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { getToken } from '@/utils/auth'
import GlobalSearch from '@/components/GlobalSearch.vue'

export default {
  name: 'App',
  components: { 
    MessageOutlined,
    UserOutlined,
    BookOutlined,
    FileTextOutlined,
    TeamOutlined,
    LogoutOutlined,
    GlobalSearch
  },
  setup() {
    const userStore = useUserStore()
    const route = useRoute()
    const router = useRouter()
    const { userStats, isLoggedIn } = storeToRefs(userStore)
    
    // 初始化加载用户信息
    if (getToken()) {
      userStore.fetchUserStats()
    }
    
    const currentMenuKey = ref(route.path)
    const menuKey = ref(`${route.path}-${userStats.value.name || 'guest'}`)
    const unreadMessages = ref(0)
    const drawerVisible = ref(false)
    const showDropdown = ref(false)

    watch([() => route.path, () => userStats.value.name], () => {
      menuKey.value = `${route.path}-${userStats.value.name || 'guest'}`
      currentMenuKey.value = route.path
    })

    const login = () => router.push('/login')
    const register = () => router.push('/register')
    const goToChat = () => router.push('/chat')
    const getPopupContainer = () => document.getElementById('app') || document.body
    const toggleDropdown = () => showDropdown.value = !showDropdown.value
    const hideDropdown = () => {
      if (!showDropdown.value) return;
      setTimeout(() => {
        const dropdownMenu = document.querySelector('.dropdown-menu');
        if (!showDropdown.value) return;
        if (!dropdownMenu || !dropdownMenu.matches(':hover')) {
          showDropdown.value = false;
        }
      }, 100);
    }
    const handleProfileMenuClick = ({ key }) => {
        const myEmail = userStats.value.email
        switch(key) {
            case 'profile':
            router.push({ path: '/profile', query: { email: myEmail } })
            break
            case 'problems':
            router.push({ path: '/profile', query: { tab: 'problems', email: myEmail } })
            break
            case 'blogs':
            router.push({ path: '/profile', query: { tab: 'blogs', email: myEmail } })
            break
            case 'friends':
            router.push({ path: '/profile', query: { tab: 'friends', email: myEmail } })
            break
            case 'logout':
            userStore.logout()
            router.push('/login')
            break
        }
    }
    
    return { 
      userStore,
      userStats,
      isLoggedIn,
      currentMenuKey,
      menuKey,
      unreadMessages,
      drawerVisible,
      showDropdown,
      login,
      register,
      goToChat,
      getPopupContainer,
      toggleDropdown,
      hideDropdown,
      handleProfileMenuClick
    }
  },
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
}

.ant-layout {
  min-height: 100vh;
}
.ant-layout-header {
  position: fixed;
  width: 100%;
  z-index: 1;
  border-bottom: 1px solid #e6e6e6;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.ant-layout-content {
  padding-top: 84px;
  /* min-height: calc(100vh - 84px); */
  min-height: unset;
  height: calc(100vh - 84px);
}

.search-container {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 10;
}

.user-actions {
  position: absolute;
  right: 50px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  align-items: center;
  height: 64px;
}

.user-actions .ant-btn {
  margin-left: 10px;
}

.user-info {
  display: flex;
  align-items: center;
  height: 100%;
  cursor: pointer;
}

.user-info .username {
  margin-right: 10px;
}




.dropdown-item {
  padding: 4px 16px;
  cursor: pointer;
  line-height: 1.5;
  transition: background-color 0.2s;
  text-align: center;
  display: block;
  pointer-events: auto;
}

.dropdown-item:hover {
  background-color: #f5f5f5;
}

.dropdown-item.danger {
  color: #ff4d4f;
}

.dropdown-item.danger:hover {
  background-color: #fff2f0;
}

.message-badge {
  cursor: pointer;
}


/* 抽屉菜单样式 */
.drawer-menu {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 8px;
}

.drawer-menu .ant-btn {
  text-align: left;
  border: none;
  box-shadow: none;
  transition: all 0.3s;
}

.drawer-menu .ant-btn:hover {
  background-color: #f5f5f5;
  transform: translateX(5px);
}

.ant-drawer-header {
  border-bottom: none;
}

.ant-drawer-body {
  padding: 16px;
}

.popover-buttons .ant-btn {
  text-align: left;
  border: none;
  box-shadow: none;
}

.popover-buttons .ant-btn:hover {
  background-color: #f5f5f5;
}

/* 下拉框样式 - 默认隐藏 */
.dropdown-content {
  display: none;
  position: absolute;
  top: 100%;
  right: 0;
  min-width: 160px;
  background-color: #fff;
  box-shadow: 0 8px 16px rgba(0,0,0,0.1);
  border-radius: 4px;
  z-index: 1000;
  margin-top: 5px;
  opacity: 0;
  transform: translateY(-10px);
  transition: opacity 0.3s ease, transform 0.3s ease;
}

/* 下拉框链接样式 */
.dropdown-content a {
  color: #333;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  transition: background-color 0.2s;
}

.dropdown-content .dropdown-item:hover {
  background-color: #f5f5f5;
}

/* 鼠标悬停在头像上时显示下拉框 */
.avatar:hover ~ .dropdown-content,
.dropdown-content:hover {
  display: block;
  opacity: 1;
  transform: translateY(0);
}
/* 下拉框与头像之间的连接区域（防止鼠标移动时下拉框消失） */
.dropdown-content::before {
  content: "";
  position: absolute;
  bottom: 100%;
  right: 0;
  width: 100%;
  height: 10px;
  background: transparent;
}
</style>
